package example.demo.route.handler.impl;

import example.demo.route.handler.SqlHandlerParent;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Invocation;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
@Order(20)
public class UpdateSqlHandler extends SqlHandlerParent {
    //SELECT id,username,real_name,sex,mobile,email,note,position_id FROM t_user WHERE id=?
    @Override
    public String getTableName(String sql) {
        //获取的table-name已经没有了前后空格
        return sql.substring(sql.lastIndexOf("FROM") + 5, sql.lastIndexOf("WHERE") - 1);
    }


//    public static void main(String[] args) {//wwt_userww 说明前后两个空格
//        SelectSqlHandler selectSqlHandler = new SelectSqlHandler();
//        System.out.println(selectSqlHandler.getTableName("SELECT id,username,real_name,sex,mobile,email,note,position_id FROM t_user WHERE id=?").
//                replaceAll(" ", "ww"));
//    }

    @Override
    public boolean isSupport(String sql) {
        return sql.contains("UPDATE") || sql.contains("update");
    }

    @Override
    public Object handler(Integer[] integers, String sql, Invocation invocation, BoundSql boundSql, Field sqlField, StatementHandler statementHandler) throws Exception {
        for (Integer integer : integers) {
            int i = integer.intValue();
            if (0 != i) {
                String tableName = getTableName(sql);
                String newTableName = tableName + i /*+ " "*/;
                String newSql = sql.replace(tableName, newTableName);
                /*替换sql*/
                sqlField.set(boundSql, newSql);


            } else {
                //0就无需替换table-name了
                return invocation.proceed();
            }
        }
        return null;
    }

}
